package com.xxl.job.executor.utils;

import javax.crypto.Cipher;
import java.security.Key;
import java.security.PrivateKey;
import java.security.PublicKey;

public class RSAUtil {

    /**
     * 加密算法
     */
    private static final String ALGORITHM = "RSA";

    /**
     * RAS 加密
     *
     * @param key       公有密钥
     * @param plaintext 明文
     * @return 密文
     * @throws Exception
     */
    public static byte[] encrypt(PublicKey key, byte[] plaintext) throws Exception {
        return cipher(ALGORITHM, key, Cipher.ENCRYPT_MODE, plaintext);
    }

    /**
     * RAS 解密
     *
     * @param key        私有密钥
     * @param ciphertext 密文
     * @return 明文
     * @throws Exception
     */
    public static byte[] decrypt(PrivateKey key, byte[] ciphertext) throws Exception {
        return cipher(ALGORITHM, key, Cipher.DECRYPT_MODE, ciphertext);
    }

    public static byte[] cipher(final String algorithm, Key key, final int mode, byte[] text) throws Exception {
        Cipher cipher = Cipher.getInstance(algorithm);
        cipher.init(mode, key);
        return cipher.doFinal(text);
    }
}

























































































































